package com.mooc.lib_ui_common.navigation

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.mooc.lib_base_application.BaseApplication
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.lang.StringBuilder

/**
 * JSON获取->解析
 * */
class AppConfig {

    //获取assets下得json文件通过io方式读取
    fun parseAssets(name:String):String{
        var result : String ?= null
        //由于读取assets文件夹下得json需要使用context
        //由于当前程序配置公共application->依赖baseapplication
        val assetsManager = BaseApplication.instance!!.assets
        var input : InputStream ?= null
        //kt中in为关键在无法直接使用:input;`in`
        try {
            input = assetsManager.open(name)
            //转换当前字节流为字符缓冲流
            val reader = BufferedReader(
                InputStreamReader(input))
            var line : String ?= null//一行String
            val buffer  = StringBuilder()
            line = reader.readLine()
            while (line != null){
                buffer.append(line)
                line = reader.readLine()
            }
            result = buffer.toString()
        }catch (e : IOException){

        }finally {
            if (input!=null){
                input.close()
            }
        }
        return result!!
    }
    //解析main tabs json
    fun getTabs():MainTabsEntity{
        val content = parseAssets("main_tabs_config.json")
        val entity : MainTabsEntity = Gson().fromJson(content,MainTabsEntity::class.java)
        return entity
    }
    //解析Destination json
    fun getDestination():HashMap<String,DestinationEntity>?{
        val type = object : TypeToken<HashMap<String,DestinationEntity>>(){
        }.type
        val content = parseAssets("destination.json")
        val hashMap : HashMap<String,DestinationEntity> = Gson().fromJson<HashMap<String,DestinationEntity>>(content,type)
        return hashMap
    }

}